import {reqGetCode,reqUserRegister,reqUserLogin,reqGetUserInfo,reqLogOut} from '@/api/index'
import  { setToken,getToken, removeToken } from '@/utils/token'
let state={
  code:'',
  token:getToken(),
  userList:{}
};
let actions={
  //注册
 async getUserCode(context,phone){
      let result =await reqGetCode(phone)

      if(result.code==200){
        
        context.commit('GETUSERCODE',result.data)
        return 'ok'
      }
      else{
        return Promise.reject(new Error('failed'))
      }
  },
  async UserRegister(context,user){
      let result=  await reqUserRegister(user)
     
      if(result.code==200){
        
        return 'ok'
      }
      else{
        return  Promise.reject(new Error(result.message))
      }
  },

  //登录
  async UserLogin(context,userLogin){
   
    let result=await reqUserLogin(userLogin)
    
    if(result.code==200){
      setToken(result.data.token)
      context.commit('USERLOGIN',result.data.token)
     
      return 'ok'
    }else{
      
      return Promise.reject(new Error(result.message))
    }
  },
  //获取用户信息
 async getUserInfo(context){
    let result=  await reqGetUserInfo()
   
    if(result.code==200){
      context.commit('GETUSERINFO',result.data)
     
      return 'ok'
    }
    else{
       return Promise.reject(new Error(result.message))
    }
  },
  //退出登录
 async  LogOutLogin(context){

    let result= await reqLogOut()
   
    if(result.code==200){
      context.commit('CLEARUSER')
    }
  }

};
let mutations={
  //注册
  GETUSERCODE(state,code){
   
    state.code=code
  },

  //登录
  USERLOGIN(state,token){

      state.token=token
  },

  //获取用户信息
  GETUSERINFO(state,userList){
      state.userList=userList
  },
  //退出登录后清除用户信息和token
  CLEARUSER(state){
    //仓库数据清空
    state.token=''
    state.userList={}
    //本地存储也清空
    removeToken()
  }

};
let getters={

};

export default {
  state,
  actions,
  mutations,
  getters
}